package com.springboot.mvc;

import com.springboot.core.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * On 2017/3/13 0013.
 * 系统异常处理
 */
@ControllerAdvice
public class SystemExceptionResolve  {
    private static final Logger log = LoggerFactory.getLogger(SystemExceptionResolve.class);

    /**
     * @param req
     * @param response
     * @param e
     *  415错误处理 处理系统因为校验参数而抛出的异常
     */
    @ExceptionHandler(value = BizException.class)
    public void _415ErrorHandler(HttpServletRequest req,HttpServletResponse response, Exception e)  {
        if (e instanceof BizException){
            BizException biz= (BizException) e;
            log.error(biz.getMessage());
            response.setCharacterEncoding("utf-8");
            //参数错误
            response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
            PrintWriter out= null;
            try {
                out=response.getWriter();
                out.append(biz.getMessage());
            } catch (IOException e1) {
                log.error(e1.getMessage());
            }finally {
                if (out!=null)
                    out.close();
            }
        }
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public String handleInvalidRequestError(IllegalArgumentException ex) {
        return ex.getMessage();
    }
}
